package com.zenithmind.document.service.impl;

import com.zenithmind.common.context.UserContext;
import com.zenithmind.document.service.UserContextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户上下文服务实现类
 * 遵循迪米特法则：封装对UserContext的直接访问
 * 遵循单一职责原则：专注于用户上下文信息管理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
public class UserContextServiceImpl implements UserContextService {

    @Override
    public String getCurrentUserId() {
        try {
            String userId = UserContext.getUserId();
            log.debug("获取当前用户ID: {}", userId);
            return userId;
        } catch (Exception e) {
            log.warn("获取当前用户ID失败", e);
            return null;
        }
    }

    @Override
    public String getCurrentUsername() {
        try {
            String username = UserContext.getUsername();
            log.debug("获取当前用户名: {}", username);
            return username;
        } catch (Exception e) {
            log.warn("获取当前用户名失败", e);
            return null;
        }
    }

    @Override
    public List<String> getCurrentUserRoles() {
        try {
            List<String> roles = UserContext.getUserRoles();
            log.debug("获取当前用户角色: {}", roles);
            return roles;
        } catch (Exception e) {
            log.warn("获取当前用户角色失败", e);
            return List.of();
        }
    }

    @Override
    public List<String> getCurrentUserPermissions() {
        try {
            // 基于角色推断权限（UserContext中暂无getPermissions方法）
            List<String> roles = getCurrentUserRoles();
            List<String> permissions = new java.util.ArrayList<>();

            // 基于角色映射权限
            for (String role : roles) {
                switch (role.toUpperCase()) {
                    case "ADMIN":
                    case "SUPER_ADMIN":
                        permissions.addAll(List.of("document:read", "document:write", "document:delete",
                            "document:admin", "document:manage"));
                        break;
                    case "AUTHOR":
                        permissions.addAll(List.of("document:read", "document:write", "document:create"));
                        break;
                    case "USER":
                        permissions.add("document:read");
                        break;
                }
            }

            log.debug("获取当前用户权限: {}", permissions);
            return permissions;
        } catch (Exception e) {
            log.warn("获取当前用户权限失败", e);
            return List.of();
        }
    }

    @Override
    public Boolean hasRole(String role) {
        try {
            List<String> roles = getCurrentUserRoles();
            boolean hasRole = roles.contains(role);
            log.debug("检查用户角色 {}: {}", role, hasRole);
            return hasRole;
        } catch (Exception e) {
            log.warn("检查用户角色失败: {}", role, e);
            return false;
        }
    }

    @Override
    public Boolean hasPermission(String permission) {
        try {
            List<String> permissions = getCurrentUserPermissions();
            boolean hasPermission = permissions.contains(permission);
            log.debug("检查用户权限 {}: {}", permission, hasPermission);
            return hasPermission;
        } catch (Exception e) {
            log.warn("检查用户权限失败: {}", permission, e);
            return false;
        }
    }

    @Override
    public String getCurrentTenantId() {
        try {
            String tenantId = UserContext.getTenantId();
            log.debug("获取当前租户ID: {}", tenantId);
            return tenantId;
        } catch (Exception e) {
            log.warn("获取当前租户ID失败", e);
            return null;
        }
    }

    @Override
    public Boolean isAuthenticated() {
        try {
            String userId = getCurrentUserId();
            boolean authenticated = userId != null && !userId.trim().isEmpty();
            log.debug("检查用户认证状态: {}", authenticated);
            return authenticated;
        } catch (Exception e) {
            log.warn("检查用户认证状态失败", e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getCurrentUserInfo() {
        Map<String, Object> userInfo = new HashMap<>();
        
        try {
            userInfo.put("userId", getCurrentUserId());
            userInfo.put("username", getCurrentUsername());
            userInfo.put("roles", getCurrentUserRoles());
            userInfo.put("permissions", getCurrentUserPermissions());
            userInfo.put("tenantId", getCurrentTenantId());
            userInfo.put("authenticated", isAuthenticated());
            
            log.debug("获取用户完整信息: {}", userInfo);
            return userInfo;
        } catch (Exception e) {
            log.warn("获取用户完整信息失败", e);
            return userInfo;
        }
    }
}
